<template>
	<view
		class="addCampaign"
		:style="{
			paddingTop: paddingHeight + 'px',
			backgroundColor: bgColor,
			minHeight: minHeight + 'px'
		}"
	>
		<nav-bar title="运动"></nav-bar>
		<view class="t-h-container">
			<view class="details">
				<view class="d_card">
					<view class="cell" @click="showCalendar = true">
						<view class="c_l">日期</view>
						<view class="c_r">{{ addInfo.sportDate }}</view>
					</view>
					<view class="cell" @click="showProject = true">
						<view class="c_l">运动项目</view>
						<view class="c_r">{{ sportProject }}</view>
					</view>
					<view class="cell" @click="showStartTime = true">
						<view class="c_l">运动开始时间</view>
						<view class="c_r">{{ addInfo.sportStartTime }}</view>
					</view>
					<view class="cell" @click="showDurationTime = true">
						<view class="c_l">持续时间</view>
						<view class="c_r"
							>{{
								addInfo.durationTime ? addInfo.durationTime : 0
							}}分钟</view
						>
					</view>
					<view class="cell">
						<view class="c_l">心率</view>
						<view class="c_r">
							<u-input
								type="number"
								inputAlign="right"
								placeholder="请输入心率"
								border="none"
								v-model="addInfo.currentHeartRate"
							></u-input>
						</view>
					</view>
					<view class="cell">
						<view class="c_l"
							>消耗热量{{ addInfo.kcal }}（Kcal）</view
						>
						<view class="c_r kcal-btn" @click="handleGetConsumeHeat"
							>计算消耗热量</view
						>
					</view>
				</view>
				<view class="d_card RER-box" style="margin-top: 32rpx">
					<view class="cell" @click="handleShowsSportRER(2)">
						<view class="c_l">运动前关联的RER测量</view>
						<view class="c_r">
							<u-icon name="edit-pen-fill" size="15"></u-icon>
						</view>
					</view>
					<view>
						<template v-if="sportBeforeForm.selectValue.length">
							<view class="cell">
								<view class="rer-table">
									<view class="rer-table-header">
										<view class="text">时间</view>
										<view class="text">代谢水平</view>
									</view>
									<view
										class="rer-table-row"
										v-for="(
											item, index
										) in sportBeforeForm.selectValue"
										:key="index"
									>
										<view class="text">{{
											item.createTime
										}}</view>
										<view class="text">{{
											item.rerLevel
										}}</view>
									</view>
								</view>
							</view>
						</template>
						<template v-else>
							<view class="not-data">
								<u-image
									width="64rpx"
									height="64rpx"
									:showMenuByLongpress="false"
									src="http://oss.antaimedical.com/images/pro/2024/10/671088aae4b0d615350f3099nt8UDhE3BBdK40e02078e4f477284337f925e806e8c9.png"
									:lazy-load="true"
								></u-image>
								<view class="text">未关联数据</view>
							</view>
						</template>
					</view>
				</view>
				<view class="d_card RER-box" style="margin-top: 32rpx">
					<view class="cell" @click="handleShowsSportRER2(3)">
						<view class="c_l">运动后关联的RER测量</view>
						<view class="c_r">
							<u-icon name="edit-pen-fill" size="15"></u-icon>
						</view>
					</view>
					<view>
						<template v-if="sportAfterForm.selectValue.length">
							<view class="cell">
								<view class="rer-table">
									<view class="rer-table-header">
										<view class="text">时间</view>
										<view class="text">代谢水平</view>
									</view>
									<view
										class="rer-table-row"
										v-for="(
											item, index
										) in sportAfterForm.selectValue"
										:key="index"
									>
										<view class="text">{{
											item.createTime
										}}</view>
										<view class="text">{{
											item.rerLevel
										}}</view>
									</view>
								</view>
							</view>
						</template>
						<template v-else>
							<view class="not-data">
								<u-image
									width="64rpx"
									height="64rpx"
									:showMenuByLongpress="false"
									src="http://oss.antaimedical.com/images/pro/2024/10/671088aae4b0d615350f3099nt8UDhE3BBdK40e02078e4f477284337f925e806e8c9.png"
									:lazy-load="true"
								></u-image>
								<view class="text">未关联数据</view>
							</view>
						</template>
					</view>
				</view>
			</view>
			<view class="next-button" @click="$u.throttle(next, 1500)"
				>记录</view
			>
		</view>

		<multiple-picker
			:title="selectMultiple.title"
			:show="selectMultiple.show"
			:columns="selectMultiple.columns"
			:defaultIndex="selectMultiple.index"
			@confirm="confirmMultiple"
			@cancel="selectMultiple.show = false"
		></multiple-picker>
		<multiple-picker
			:title="selectMultiple2.title"
			:show="selectMultiple2.show"
			:columns="selectMultiple2.columns"
			:defaultIndex="selectMultiple2.index"
			@confirm="confirmMultiple2"
			@cancel="selectMultiple2.show = false"
		></multiple-picker>
		<my-calendar
			:monthNum="24"
			:defaultDate="defaultDate"
			:maxDate="maxDate"
			@confirm="selectDate"
			:minDate="minDate"
			:show="showCalendar"
			color="#545DDE"
			closeOnClickOverlay
			@close="showCalendar = false"
		></my-calendar>
		<u-picker
			:show="showProject"
			keyName="name"
			:defaultIndex="[0]"
			@confirm="selectProject"
			@cancel="showProject = false"
			@close="showProject = false"
			closeOnClickOverlay
			confirmColor="#545DDE"
			:columns="columns"
		></u-picker>
		<u-datetime-picker
			@confirm="selectDurationTime"
			@cancel="showDurationTime = false"
			@close="showDurationTime = false"
			closeOnClickOverlay
			:show="showDurationTime"
			mode="time"
		></u-datetime-picker>
		<u-datetime-picker
			@confirm="selectStartTime"
			@cancel="showStartTime = false"
			@close="showStartTime = false"
			:show="showStartTime"
			v-model="addInfo.sportStartTime"
			closeOnClickOverlay
			mode="time"
		></u-datetime-picker>
		<u-picker
			:show="showGrade"
			:defaultIndex="[0]"
			@confirm="selectGrade"
			@cancel="showGrade = false"
			@close="showGrade = false"
			confirmColor="#545DDE"
			:columns="columnsGrade"
			closeOnClickOverlay
		></u-picker>
	</view>
</template>

<script>
import {
	addSportRecord,
	findSportType,
	findSportMeasureRecord,
	getConsumeHeat
} from '@/api/index.js'
import { mapGetters } from 'vuex'
import multiplePicker from '@/components/multiple-picker/multiple-picker.vue'
import myCalendar from '@/components/myCalendar/myCalendar.vue'
const dayjs = require('@/utils/dayjs.min.js')
export default {
	data() {
		return {
			paddingHeight: uni.getStorageSync('navbarHeight'),
			userId: uni.getStorageSync('userId'),
			dataList: [],
			columns: [], // 项目列表
			columnsGrade: [['低', '中', '高']],
			showSport: true,
			showProject: false,
			showDurationTime: false,
			showGrade: false,
			showStartTime: false,
			showCalendar: false,
			defaultDate: [],
			maxDate: undefined,
			minDate: undefined,
			addInfo: {
				durationTime: '10',
				sportDate: '',
				sportProject: 1,
				sportStartTime: '',
				currentHeartRate: '',
				kcal: ''
				// strengthGrade: '低',
			},
			sportProject: '步行',
			tag: undefined,
			sportBeforeForm: {
				selectValue: [],
				selectIndex: []
			},
			sportAfterForm: {
				selectValue: [],
				selectIndex: []
			},
			selectMultiple: {
				title: '运动前',
				show: false,
				index: [],
				columns: []
			},
			selectMultiple2: {
				title: '运动后',
				show: false,
				index: [],
				columns: []
			},
			sportBeforeList: [], //运动前rer
			sportAfterList: [], //运动后rer
			sportType: ''
		}
	},
	computed: {
		...mapGetters({
			userInfo: 'getUserInfo'
		})
	},
	components: {
		myCalendar,
		multiplePicker
	},
	onLoad(OPTIONS) {
		if (OPTIONS.tag) this.tag = OPTIONS.tag
		this.maxDate = dayjs().format('YYYY-MM-DD')
		this.minDate = dayjs(dayjs(this.maxDate).subtract(365, 'day')).format(
			'YYYY-MM-DD'
		)
		this.defaultDate[0] = OPTIONS.day
		this.addInfo.sportDate = OPTIONS.day.replaceAll('-', '/')
		this.addInfo.sportStartTime = dayjs().format('HH:mm')
		this.fetchData()
		this.getFindSportMeasureRecord(2)
		this.getFindSportMeasureRecord(3)
	},
	methods: {
		// 计算热量
		handleGetConsumeHeat() {
			let params = {
				bodyId: this.userInfo.id || this.userInfo.bodyId,
				currentHeartRate: this.addInfo.currentHeartRate,
				durationTime: this.addInfo.durationTime
			}
			getConsumeHeat(params).then((res) => {
				if (res.code == 200) {
					this.addInfo.kcal = res.data
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}
			})
		},
		// 关联rer  start
		confirmMultiple(e) {
			this.sportBeforeForm.selectValue = e.selected
			this.sportBeforeForm.selectIndex = e.value
			this.selectMultiple.show = false
		},
		confirmMultiple2(e) {
			this.sportAfterForm.selectValue = e.selected
			this.sportAfterForm.selectIndex = e.value
			this.selectMultiple2.show = false
		},
		handleShowsSportRER(sportType) {
			this.sportType = sportType
			this.selectMultiple.show = true
			this.selectMultiple.columns = this.sportBeforeList
			this.selectMultiple.index = this.sportBeforeForm.selectIndex
		},
		handleShowsSportRER2(sportType) {
			this.sportType = sportType
			this.selectMultiple2.show = true
			this.selectMultiple2.columns = this.sportAfterList
			this.selectMultiple2.index = this.sportAfterForm.selectIndex
		},
		// 关联rer  end
		// 获取rer 测量数据
		getFindSportMeasureRecord(sportType) {
			let params = {
				sportDate: dayjs(this.addInfo.sportDate).format('YYYY-MM-DD'),
				sportType,
				userId: this.userInfo.userId
			}
			findSportMeasureRecord(params).then((res) => {
				let arr = res.data.map((val) => {
					return {
						label: `${val.createTime} 代谢水平:${val.rerLevel}`,
						createTime: val.createTime,
						rerLevel: val.rerLevel,
						value: val.id
					}
				})
				if (sportType == 2) {
					this.sportBeforeList = arr
				} else {
					this.sportAfterList = arr
				}
			})
		},

		// 获取运动类型
		async fetchData() {
			uni.showLoading({
				title: '加载中...'
			})
			try {
				const res = await findSportType()
				if (res.code == 200) {
					this.columns[0] = res.data
				}
			} catch (e) {
				//TODO handle the exception
			}
			uni.hideLoading()
		},

		async next() {
			uni.showLoading({
				title: '加载中...'
			})
			let params = {
				userId: this.userId,
				bodyId: this.userInfo.id || this.userInfo.bodyId,
				time: dayjs().format('YYYY-MM-DD hh:mm:ss'),
				beforeRerRecord: this.sportBeforeForm.selectIndex.toString(),
				afterRerRecord: this.sportAfterForm.selectIndex.toString(),
				...this.addInfo
			}
			try {
				const res = await addSportRecord(params)
				uni.hideLoading()
				if (res.code == 200) {
					uni.showToast({
						title: '添加成功'
					})
					setTimeout(() => {
						// 跳转测量
						uni.$emit('refreshData')
						if (this.tag) {
							uni.redirectTo({
								url: `/pagesA/health/device/connect/index?tag=${this.tag}&sportId=${res.data}`
							})
						} else {
							uni.navigateBack()
						}
					}, 1500)
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}
			} catch (e) {
				//TODO handle the exception
				uni.hideLoading()
			}
		},
		// 确定选择项目
		selectProject(e) {
			console.log(e)
			this.sportProject = e.value[0].name
			this.addInfo.sportProject = e.value[0].id
			this.showProject = false
		},
		// 确定选择等级
		selectGrade(e) {
			console.log(e)
			this.addInfo.strengthGrade = e.value[0]
			this.showGrade = false
		},
		// 确定选择开始时间
		selectStartTime() {
			this.showStartTime = false
		},
		// 选择日期
		selectDate(e) {
			this.addInfo.sportDate = e[0].replaceAll('-', '/')
			this.defaultDate[0] = e[0]
			this.showCalendar = false
		},
		// 确定选择持续时间
		selectDurationTime(e) {
			this.showDurationTime = false
			let arr = e.value.split(':')
			let num
			if (Number(arr[0]) > 0) {
				num = Number(arr[0]) * 60 + Number(arr[1])
			} else {
				num = Number(arr[1])
			}
			this.addInfo.durationTime = String(num)
		},
		goDetails() {
			uni.navigateTo({
				url: `/pagesA/device/info/campaign/add?type=measure`
			})
		}
	}
}
</script>

<style lang="scss">
page {
	min-height: 100%;
	background: #f5f6fa;
}
</style>
<style lang="scss" scoped>
.next-button {
	width: 423rpx;
	height: 85rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 64rpx;
    margin: 58rpx auto 0;
	background: #1f2434;
	font-family: PingFang SC, PingFang SC;
	font-weight: 400;
	font-size: 28rpx;
	color: #ffffff;
	line-height: 38rpx;
	text-align: center;
	font-style: normal;
	text-transform: none;
}
.t-h-container {
	padding: 0 26rpx 180rpx 26rpx;
	.details {
		.d_card {
			background: #fff;
			padding: 0 32rpx;
			border-radius: 32rpx;
			.cell {
				height: auto;
				padding: 32rpx 0;
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				font-size: 28rpx;
				color: #666666;
				border-bottom: 2rpx solid #e6ebf5;
				&:last-child {
					border-bottom: 0;
				}
				.c_l {
					color: #1f2434;
				}
				.c_r {
					font-weight: 500;
					font-size: 28rpx;
					color: rgba(31, 36, 52, 0.5);
					/deep/.u-input__content__field-wrapper__field {
						font-weight: 500;
						font-size: 28rpx;
						color: rgba(31, 36, 52, 0.5);
					}
				}
				.kcal-btn {
					width: 225rpx;
					height: 72rpx;
					background: #1f2434;
					border-radius: 24rpx;
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					font-size: 24rpx;
					color: #ffffff;
					display: flex;
					justify-content: center;
					align-items: center;
				}
			}
		}
		.RER-box {
			.cell {
				border-bottom: 0;
				.c_l {
					color: #1f2434;
				}
			}
			.rer-table {
				border-radius: 32rpx;
				overflow: hidden;
				.text {
					width: 310rpx;
					height: 64rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					border: 2rpx solid #fff;
				}
				.rer-table-header {
					display: flex;
					justify-content: center;
					align-items: center;
					background: #fafafa;
				}
				.rer-table-row {
					display: flex;
					justify-content: center;
					align-items: center;
					background: #f4eefa;
				}
			}
			.not-data {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				padding-bottom: 32rpx;
				.text {
					margin-top: 16rpx;
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					font-size: 24rpx;
					color: #999999;
				}
			}
		}
	}
}
</style>
